package com.cj.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author：weiwei
 * @name：DBUtils
 * @Date：2024/9/20 16:24
 */
public class DBUtils {
    //characterEncoding=utf-8   设置数据库编码为 utf-8
    private static String url = "jdbc:mysql://localhost:3306/cj_system?characterEncoding=utf-8";
    private static String user = "root";
    private static String password = "lql1511..";
//    private static String jdbcName = "com.mysql.jdbc.Driver";//加载JDBC驱动
//    mysql版本是8.0以上，加载JDBC驱动
    private static String jdbcName = "com.mysql.cj.jdbc.Driver";

    private Connection conn = null;

    /**
     * 连接数据库的方法
     * @return
     */
    public Connection getConnection(){
        try {
            Class.forName(jdbcName);
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接成功！YES");
        } catch (SQLException throwables) {
            System.out.println("数据库连接失败！NO!!");
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库的连接
     */
    public void closeConn(){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
